package com.yun.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.blog.bean.Result;
import com.yun.blog.bean.User;
import com.yun.blog.service.UserService;
import com.yun.blog.utils.FileUtils;
import com.yun.blog.utils.JwtUtils;
import com.yun.blog.utils.Md5;
import com.yun.blog.utils.QianiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Map;


/**
 * 用户接口
 * title        : UserController
 * projectName  : dantouBlog-back
 * author       : simple
 * date         : 2022/11/24下午2:07
 */


@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理接口")
public class UserController {

    @Resource
    UserService userService;

    @GetMapping("/getAll")
    @ApiOperation("分页获取所有用户信息")
    public Result getAll(@RequestParam(defaultValue = "10") Integer pageSize,
                         @RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "") String searchText) {

        try {
            Page<User> userPage = userService.customPage(new Page<>(pageNum, pageSize), searchText);
            return Result.success().add("page", userPage);
        } catch (Exception e) {
            log.error("获取用户列表失败：错误信息为：{}", e.getMessage());
            return Result.fail("获取用户列表失败：错误信息为：" + e.getMessage());
        }

    }

    @PostMapping("/updateUser")
    @ApiOperation("更新用户信息")
    public Result updateUser(@RequestBody User user) {
        // 先判断用户名是否存在
        User user1 = userService.getByUserUsername(user.getUserUsername());
        if (user1 != null && !user1.getUserId().equals(user.getUserId())) {
            return Result.fail("用户名已存在");
        }
        // 如果表单填写了密码，就修改密码
        if (StringUtils.hasText(user.getUserPassword())){
            user.setUserPassword(Md5.md5(user.getUserPassword()));
        }

        try {
            userService.saveOrUpdate(user);
        } catch (Exception e) {
            log.error("修改用户信息失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("修改成功！");
    }

    @GetMapping("/deleteUser")
    @ApiOperation("根据id删除用户")
    public Result deleteUser(Integer userId) {
        try {
            userService.removeById(userId);
        } catch (Exception e) {
            log.error("删除失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("删除成功！");
    }

    @PostMapping("/deleteMany")
    @ApiOperation("根据id列表批量删除用户")
    public Result deleteMany(@RequestBody ArrayList<Integer> ids) {
        // log.info("ids:{}", ids);
        try {
            userService.removeByIds(ids);
        } catch (Exception e) {
            log.error("删除失败：错误信息为：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
        return Result.success("删除成功！");
    }


    // 检查token合法性
    @GetMapping("/checkToken")
    @ApiOperation(value = "检查token合法性",notes = "token 在请求头")
    public boolean checkToken(HttpServletRequest request) {
        return JwtUtils.checkToken(request);
    }

    @PostMapping("/uploadHeadImg")
    @ApiOperation("上传图片")
    public Result uploadHeaderImg(MultipartFile headerImg) {
        Result fail = Result.fail();
        if (headerImg == null || headerImg.isEmpty()) {
            fail.setMsg("图片不能为空！");
            return fail;
        }
        String filename = headerImg.getOriginalFilename();
        boolean allowPic = FileUtils.isAllowPic(filename);
        if (!allowPic) {
            fail.setMsg("图片类型不正确！");
            return fail;
        }

        try {
            // String imgPath = FileUtils.saveImg(headerImg, "userHeaderImg");
            String imgPath = QianiuUploadUtils.upload(headerImg,"headImg");
            Result success = Result.success("图片保存成功！");
            success.add("imgPath", imgPath);
            return success;
        } catch (Exception e) {
            log.error("图片保存失败！，错误信息为：{}", e.getMessage());
            fail.setMsg("图片保存失败！，错误信息为：" + e.getMessage());
            return fail;
        }
    }


    /**
     * 检查账号是否可用
     *
     * @param username 账号
     * @param userId   id
     * @return boolean 是否可用
     **/
    @GetMapping("/checkUsernameCanUse")
    @ApiOperation("检查用户名是否可用")
    public boolean checkUsernameCanUse(String username, Integer userId) {
        if (!StringUtils.hasText(username) || username.length() > 12) {
            return false;
        }
        QueryWrapper<User> query = Wrappers.query();
        query.eq("user_username", username);
        User one = userService.getOne(query);
        // 如果前端传递的id是null，就是新增，这种情况下，one==null表示用户名可用
        // 如果前端传递了id，查询的id==传递的id，表示在修改本账号的其他信息，
        // 如果查到的id ！= 传递的id，表示修改username但是被占用
        if (one == null || one.getUserId().equals(userId)) {
            return true;
        }
        return false;
    }


    @GetMapping("/getUserInfo")
    @ApiOperation(value = "通过token获取用户信息",notes = "token 在请求头中，通过解析token得到id，查询用户信息")
    public User getUserInfo(HttpServletRequest request) {
        User user = userService.getById(JwtUtils.getMemberIdByToken(request));
        user.setUserPassword("");
        return user;
    }

    @PostMapping("editSelfInfo")
    @ApiOperation(value = "修改用户自己的信息")
    public Result editSelfInfo(@RequestBody User user, HttpServletRequest request) {
        log.info("user:{}", user);
        // 找到登录的userid，设置好id
        Integer userId = JwtUtils.getMemberIdByToken(request);
        user.setUserId(userId);
        // 如果设置了密码，就验证密码长度并修改密码
        String userPassword = user.getUserPassword();
        if (StringUtils.hasText(userPassword)) {
            if (userPassword.length() < 6) {
                return Result.fail("新密码长度要大于等于6位！");
            }
            user.setUserPassword(Md5.md5(userPassword));
        } else {
            user.setUserPassword(null);
        }
        userService.updateById(user);
        return Result.success("修改成功");
    }

    @PostMapping("editPassword")
    @ApiOperation(value = "修改密码")
    public Result editPassword(@RequestBody Map<String, String> map, HttpServletRequest request) {
        log.info("map:{}", map);
        Integer userId = JwtUtils.getMemberIdByToken(request);
        User user = userService.getById(userId);
        String oldPassword = map.get("oldPassword");
        // 对比旧密码是否正确
        if (!Md5.md5(oldPassword).equals(user.getUserPassword())) {
            return Result.fail("旧密码输入错误！");
        }
        // 验证新密码长度
        String newPassword = map.get("newPassword");
        if (newPassword.length() < 6) {
            return Result.fail("新密码长度要大于等于6位！");
        }
        user.setUserPassword(Md5.md5(newPassword));
        userService.updateById(user);
        return Result.success("修改成功！");
    }


}
